package com.yami.shop.common.i18n;


import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;
import java.util.Objects;

/**
 * RequestContextFilter 会传入默认的Locale，优先级(-105) 要比RequestContextFilter优先级高
 * @author LGH
 */
@Slf4j
@Component
@Order(-104)
public class YamiLocaleChangeFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String newLocale = request.getHeader("locale");

        log.info("前端传递的locale参数："+newLocale);
        if (newLocale == null) {
            newLocale = "zh";
        }else{
            if(Objects.equals(newLocale,"zh_CN")||Objects.equals(newLocale,"zh_cn")){
                newLocale = "zh";
            }
//            String lowerLocale = newLocale.toLowerCase();
//            LocaleContextHolder.setLocale(new Locale(lowerLocale));
            LocaleContextHolder.setLocale(new Locale(newLocale));
            Locale locale = LocaleContextHolder.getLocale();
            log.info("修改后的locale参数："+locale.getLanguage());
//            LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
//            if (localeResolver == null) {
//                throw new IllegalStateException(
//                        "No LocaleResolver found: not in a DispatcherServlet request?");
//            }
//            try {
//                localeResolver.setLocale(request, response, StringUtils.parseLocale(newLocale));

//            }
//            catch (IllegalArgumentException ex) {
//                    throw ex;
//            }
        }
        LocaleContextHolder.setLocale(new Locale(newLocale));
        Locale locale = LocaleContextHolder.getLocale();
        log.info("修改后的locale参数："+locale.getLanguage());
        filterChain.doFilter(request, response);
    }
}
